﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JCFramework.Extensions
{
    public static class EnumerableExtensions
    {
        public static bool HasValue<T>(this IEnumerable<T> list)
        {
            if (list == null) return false;

            return list.Any();
        }

        public static string JoinString<T>(this IEnumerable<T> list, string separator)
        {
            if (list == null) return String.Empty;
            return String.Join(separator, list.Select(s => s.ToString()).ToArray());
        }

        public static void AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> collection)
        {
            foreach (var item in collection)
            {
                list.AddDistinct(item);
            }
        }

        public static void AddDistinct<T>(this IList<T> list, T t)
        {
            if (!list.Contains(t))
            {
                list.Add(t);
            }
        }

        public static void ForEach<T>(this IEnumerable<T> dict, Action<T> action)
        {
            if (dict == null) return;

            foreach (var keyValue in dict)
            {
                action(keyValue);
            }
        }

        public static Dictionary<TKey, List<TValue>> ToListDictionary<TKey, TValue>(
            this IEnumerable<TValue> list, 
            Func<TValue, TKey> getter)
        {
            Dictionary<TKey, List<TValue>> result = new Dictionary<TKey, List<TValue>>();

            foreach (var value in list)
            {
                var key = getter(value);

                if (result.Keys.Contains(key))
                {
                    if (!result[key].Contains(value))
                    {
                        result[key].Add(value);
                    }
                }
                else
                {
                    result.Add(key, new List<TValue> { value });
                }
            }

            return result;
        }

        public static IEnumerable<TResult> Zip<TFirst, TSencond, TResult>(
            this IEnumerable<TFirst> first,
            IEnumerable<TSencond> sencond,
            Func<TFirst, TSencond, TResult> func)
        {
            var firsttor = first.GetEnumerator();
            var sencondtor = sencond.GetEnumerator();

            while (firsttor.MoveNext())
            {
                if (sencondtor.MoveNext())
                {
                    yield return func(firsttor.Current, sencondtor.Current);
                }
            }
        }
    }
}
